package com.example.redis02.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@RestController
@Slf4j
@RequestMapping("/goods")
public class RedisController {

    @Resource
    private RedissonClient redisson;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${server.port}")
    private String port;


    private static final String LOCK_STRING="redissonClient";

    @GetMapping(value = "getNum")
    public Object getNum(){
        RLock lock = redisson.getLock("lockName");
        try{
            // 1. 最常见的使用方法
            //lock.lock();
            // 2. 支持过期解锁功能,10秒钟以后自动解锁, 无需调用unlock方法手动解锁
            //lock.lock(10, TimeUnit.SECONDS);
            // 3. 尝试加锁，最多等待2秒，上锁以后8秒自动解锁
            boolean res = lock.tryLock(2, 8, TimeUnit.SECONDS);
            //成功
            if(res){
                //处理业务
                String value = stringRedisTemplate.opsForValue().get("goods:M000001");
                if(value==null){
                    stringRedisTemplate.opsForValue().set("goods:M000001",String.valueOf(100));
                }else{
                    Integer num = Integer.parseInt(value)-1;
                    if(num>0){
                        log.info("库存剩余"+num);
                        stringRedisTemplate.opsForValue().set("goods:M000001",String.valueOf(num));
                    }else{
                       log.info("库存已卖完请稍后"+num);
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //释放锁
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return  port;
    }
}
